package megrez.bussiness.system.entity;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.Table;

import org.springframework.beans.BeanUtils;

import lombok.Getter;
import lombok.Setter;
import megrez.common.jpa.AbstractIdEntity;

/**
 * 地区
 * 
 * @author Lucky Yang
 * @since 0.0.1
 */
@Entity
@Getter
@Setter
@Table(name = "area")
public class Area extends AbstractIdEntity {
    public final static String PATH_SEP = "/";

    /**
     * 上级
     */
    @ManyToOne
    @JoinColumn(name = "parentId")
    private Area parent;

    /**
     * 代码
     */
    @Column(nullable = false, unique = true, updatable = false)
    private String code;

    /**
     * 名称
     */
    @Column(nullable = false)
    private String name;

    /**
     * code路径
     */
    private String pathCode;

    /** 是否末级 */
    private Boolean isLeaf;

    /**
     * 子地区
     */
    @OneToMany(mappedBy = "parent", cascade = { CascadeType.PERSIST })
    private List<Area> children = new ArrayList<>();

    public Area() {
    }

    public Area(String code, String name) {
        this.code = code;
        this.name = name;
    }

    public Area(Area parent, String code, String name) {
        this.parent = parent;
        this.code = code;
        this.name = name;
    }

    @PrePersist
    @PreUpdate
    public void preAction() {
        if (parent != null) {
            pathCode = parent.getPathCode() + PATH_SEP + code;
        } else {
            pathCode = code;
        }

        if (isLeaf == null) {
            isLeaf = true;
        }
    }

    public void copy(Area source) {
        BeanUtils.copyProperties(source, this, "id,parent,children,pathCode".split(","));
    }
}
